package CompletableFuturefd;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
@Component
@Slf4j
public class PoolManager {

    private static final int QUEUE_SIZE = 1024;

    private static AtomicInteger atomicInteger = new AtomicInteger();

    /**
     * 商品导入导入线程队列
     */
    private static LinkedBlockingQueue<Runnable> importGoodsQueue = new LinkedBlockingQueue<Runnable>(QUEUE_SIZE);
    private static ExecutorService importGoodsExecutor = new ThreadPoolExecutor(1, 1, 0L,
            TimeUnit.MILLISECONDS, importGoodsQueue, r -> {
        Thread thread = new Thread(r);
        // 在 Java 语言中线程分为两类：用户线程和守护线程，
        // 默认情况下我们创建的线程或线程池都是用户线程，守护线程是为用户线程服务的，
        // 当一个程序中的所有用户线程都执行完成之后程序就会结束运行，
        // 程序结束运行时不会管守护线程是否正在运行
        thread.setDaemon(true);
        thread.setName("import-model-thread-" + atomicInteger.getAndIncrement());
        return thread;
    });

    public static void importGoodsBlocking(Runnable runnable) throws Exception {
        if (importGoodsQueue.size() >= QUEUE_SIZE) {
            throw new Exception("队列已满！");
        }
        importGoodsExecutor.execute(runnable);
    }
}
